﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using SyncService.Core.Model;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Threading.Tasks;
using static NPOI.HSSF.UserModel.HeaderFooter;
using NPOI.SS.Formula.Functions;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "inventoryToInstorageService")]
    public class InventoryToInstorageService:AssetSyncServiceBase
    {
        protected override string NotifyGroupName => "";
        private ILogger<AssetInstorageService> _logger = null;
        private IMemoryCache? _cache = null;

        private bool IsNotPush = false;
        public InventoryToInstorageService() : base(YdConstants.YIDEA, "Esb", "")
        {
        }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _logger = Resolver.Resolve<ILogger<AssetInstorageService>>();
            _cache = Resolver.Resolve<IMemoryCache>();
        }
        public override void ExecuteCore()
        {
            _logger.LogInformation("盘盈转入库不做任何处理");
            //var data = (AssetSyncEvent)State!;
            //try
            //{
            //    Thread.Sleep(4000);
            //    _logger.LogInformation("开始处理盘盈转入库");
            //    //YideaClient

            //    var serialNo = data!.Data!["SerialNo"]!.ToString();
            //    if (serialNo.Substring(0, 3) == "AIN")
            //    {
            //        QueryParam instanceQueryParam = new QueryParam();
            //        instanceQueryParam.FilterString = "appInstanceCode="+serialNo;
            //        List<InstanceModel> instances = YideaClient.GetInstanceList(instanceQueryParam).ToList();
            //        if (instances.Count == 0) {
            //            _logger.LogInformation("盘点单" + serialNo + "流程实例数量为0，不需要转入库单");
            //            return;
            //        }

            //        string userId = data.Data["operator"]["id"].ToString();
            //        string userName = data.Data["operator"]["name"].ToString();
            //        AssetInStorage assetInStorage = new AssetInStorage();
            //        assetInStorage.Status = 1;
            //        var instorageAssetType = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "InstorageAssetType");
            //        var companyCodeValueField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "CompanyCode");
            //        var companyIdValueField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "CompanyId");
            //        var invoiceFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "发票号码");
            //        var comapnyCodeFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码");
            //        var centerCodeFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心码");
            //        var applicationSerialNoFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "费控申请单号");
            //        var applicationRowFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "费控申请行号");
            //        var purchaseOrderFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "采购订单号");
            //        var reciveFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "收货单号");
            //        var companyNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司名称");
            //        var assetcenterNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名称");
            //        var companyNewNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司名");
            //        var assetcenterNewNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");

            //        var assetBrandField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "品牌");
            //        var assetMasterTopTypeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "资产大类");
            //        var assetMasterSourceFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "资产来源");
            //        var isGuozhangField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "是否过账");
            //        var assetAdressDaleiField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地大类");
            //        var assetShopCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
            //        var assetShopNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺名称");
            //        var assetAdressField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地");

            //        var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            //        var companyMasterNameField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");

            //        var centerCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            //        var centerNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");

                 

            //        var company = UserDefines.First(x => x.Name == "公司主数据");
            //        var center = UserDefines.First(x => x.Name == "成本中心");
            //        var mainform = new YideaMainFormAssetInStorage()
            //        {
            //            Date = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")),
            //            CreateDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")),
            //            Creator = new JsonObject
            //            {
            //                ["value"] = userId,
            //                ["label"] = userName
            //            },
            //            OwnCompany = new JsonObject
            //            {
            //                ["value"] = companyIdValueField.FieldId,//修改值
            //                ["code"] = companyCodeValueField.FieldId,//修改值
            //                ["label"] = "宝胜集团",
            //                ["type"] = "departmentName"
            //            },
            //            Source = new JsonObject
            //            {

            //                ["value"] = "7",
            //                ["label"] = "盘盈",
            //                ["color"] = new JsonObject
            //                {
            //                    ["backgroundColor"] = "#45cb7f",
            //                    ["foreColor"] = "#ffffff"

            //                },
            //            },
            //            ReceiptSerialNumber = "",
            //            ManualReceiptNumber = "",
            //            FlowFlag="2"
            //        };
            //        assetInStorage.FormJson = JsonSerializer.Serialize(mainform);
            //        var assetList = new JsonArray();
            //        QueryParam inventoryQueryParam = new QueryParam();
            //        inventoryQueryParam.Keyword = serialNo;
            //        inventoryQueryParam.FilterString = "inventoryStateIn=3,4";
            //        List<AssetInventory> assets = FromClient.GetAssetInventoryItems(inventoryQueryParam).ToList();


            //        QueryParam queryParam = new QueryParam();
            //        queryParam.FilterString = "id=" + userId;
            //        List<User> users= YideaClient.GetUsers(queryParam).ToList();
            //        string employeeNo = "",employeeName="";
            //        if (users.Count > 0) {
            //            employeeNo = users[0].EmployeeNo;
            //            employeeName=users[0].EmployeeName;
            //        }
            //        foreach (var asset in assets)
            //        {
            //            var topAssetType = GetAssetTypeByCode(asset.RevisedAssetTypeCode);
            //            var assetTypeName = topAssetType["hierarchyName"].ToString();
            //            if (!instorageAssetType.FieldId.Contains("," + topAssetType["topTypeCode"] + ",")) {
            //                continue;
            //            }
            //            var companyCodeValue= asset.ExtensionFields.Where(e => e.Model == comapnyCodeFiled.FieldId).Select(e => e.Value).First();
            //            JsonObject companyDetail = new JsonObject();
            //            string companyName = "";
            //            var companyData = YideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam()
            //            {
            //                FilterString = "[{\"field\":\"" + companyMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"公司代码\",\"opt\":\"Equal\",\"val\":\"" + companyCodeValue + "\"}]"
            //            }).ToList();
            //            if (companyData.Count > 0)
            //            {
            //                companyDetail = JsonNode.Parse(JsonSerializer.Serialize(companyData[0].Data)).AsObject();
            //                companyDetail.Remove("dataJson");
            //                companyDetail[companyMasterCodeField.FieldId] = companyCodeValue;
            //                companyName = asset.ExtensionFields.Where(e => e.Model == companyNewNameField.FieldId).Select(e => e.Value).First();
            //                companyDetail[companyMasterNameField.FieldId] = companyName;
            //            }
            //            var centerValue = asset.ExtensionFields.Where(e => e.Model == centerCodeFiled.FieldId).Select(e => e.Value).First();
            //            JsonObject centerDetail = new JsonObject();
            //            string centerName = "";
            //            var centerData = YideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam()
            //            {
            //                FilterString = "[{\"field\":\"" + centerCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"成本中心\",\"opt\":\"Equal\",\"val\":\"" + centerValue + "\"}]"
            //            }).ToList();
            //            if (centerData.Count > 0)
            //            {
            //                centerDetail = JsonNode.Parse(JsonSerializer.Serialize(centerData[0].Data)).AsObject();
            //                centerDetail.Remove("dataJson");
            //                centerDetail[centerCodeField.FieldId] = centerValue;
            //                centerName= asset.ExtensionFields.Where(e => e.Model == assetcenterNewNameField.FieldId).Select(e => e.Value).First();
            //                centerDetail[centerNameField.FieldId] = centerName;
            //            }
            //            var applicationSerialNoValue = asset.ExtensionFields.Where(e => e.Model == applicationSerialNoFiled.FieldId).Select(e => e.Value).First();
            //            var applicationRowValue = asset.ExtensionFields.Where(e => e.Model == applicationRowFiled.FieldId).Select(e => e.Value).First();
            //            var purchaseOrderValue= asset.ExtensionFields.Where(e => e.Model == purchaseOrderFiled.FieldId).Select(e => e.Value).First();
            //            var assetMasterTopType = asset.ExtensionFields.Where(e => e.Model == assetMasterTopTypeField.FieldId).Select(e => e.Value).First();

            //            //店铺，存放地
            //            string adressDalei = asset.ExtensionFields.Where(e=>e.Model== assetAdressDaleiField.FieldId).Select(e=>e.Value).First();
            //                var shopCode = asset.ExtensionFields.Where(e => e.Model == assetShopCodeField.FieldId).Select(e => e.Value).First();
            //            var adressDataJson = "\"\"";
            //            var shopDataJson = "\"\"";
            //            if (adressDalei != "")
            //            {
            //                adressDataJson = "{\"id\":\"" + adressDalei + "\",\"value\":\"" + adressDalei + "\",\"label\":\"" + adressDalei + "\"}";
            //            }
            //            if (shopCode != "")
            //            {
            //                shopDataJson = "{\"id\":\"" + shopCode + "\",\"value\":\"" + shopCode + "\",\"label\":\"" + shopCode + "\"}";
            //            }
            //            var shopname = asset.ExtensionFields.Where(e => e.Model == assetShopNameField.FieldId).Select(e => e.Value).First();
            //            var address = asset.ExtensionFields.Where(e => e.Model == assetAdressField.FieldId).Select(e => e.Value).First();
            //            var assetSourceValue = asset.ExtensionFields.Where(e => e.Model == assetMasterSourceFiled.FieldId).Select(e => e.Value).First();
            //            var isGuozhang = assetSourceValue == "零元列管" ? "是" : "否";
            //            assetList.Add(new JsonObject
            //            {

            //                ["name"] = asset.Name,
            //                ["specs"] = asset.Specification,
            //                ["EXT_" + assetBrandField.FieldId] = "",
            //                ["assetTypeName"] = assetTypeName,
            //                ["districtName"] = asset.RevisedDistrictName,
            //                ["supervisor"] = employeeName,
            //                ["supervisorNo"] = employeeNo,
            //                ["purchaseDate"] = DateTime.Now.ToString("yyyy-MM-dd"),
            //                ["amount"] = "0",
            //                ["EXT_" + assetAdressField.FieldId] = address,
            //                ["EXT_" + assetShopNameField.FieldId] = shopname,
            //                ["EXT_" + assetShopCodeField.FieldId + "_VALUE"] = shopCode,
            //                ["EXT_" + assetAdressDaleiField.FieldId + "_VALUE"] = adressDalei,
            //                ["EXT_" + assetMasterTopTypeField.FieldId + "_VALUE"] = assetMasterTopType,
            //                ["EXT_" + assetMasterTopTypeField.FieldId] = new JsonObject
            //                   {
            //                       ["value"] = assetMasterTopType,
            //                       ["label"] = assetMasterTopType,
            //                       ["color"] = new JsonObject
            //                       {
            //                           ["backgroundColor"] = "#52a8ff",
            //                           ["foreColor"] = "#ffffff"
            //                       }
            //                   },
            //                ["EXT_" + invoiceFiled.FieldId] = "0",
            //                ["EXT_" + assetMasterSourceFiled.FieldId + "_VALUE"] = assetSourceValue,
            //                ["EXT_" + assetMasterSourceFiled.FieldId] = new JsonObject
            //                {
            //                    ["value"] = assetSourceValue,
            //                    ["label"] = assetSourceValue,
            //                    ["color"] = new JsonObject
            //                    {
            //                        ["backgroundColor"] = "#4fbbe0",
            //                        ["foreColor"] = "#ffffff"
            //                    }
            //                },
            //                ["EXT_" + comapnyCodeFiled.FieldId] = companyCodeValue,
            //                ["EXT_" + companyNewNameField.FieldId]=companyName,
            //                ["EXT_" + centerCodeFiled.FieldId] = centerValue,
            //                ["EXT_" + assetcenterNewNameField.FieldId]=centerName,
            //                ["EXT_" + applicationSerialNoFiled.FieldId] = applicationSerialNoValue,
            //                ["EXT_" + applicationRowFiled.FieldId] = applicationRowValue,
            //                ["EXT_" + purchaseOrderFiled.FieldId] = purchaseOrderValue,
            //                ["EXT_" + reciveFiled.FieldId] = serialNo,
            //                ["EXT_" + isGuozhangField.FieldId] = isGuozhang,
            //                ["dataJson"] = "{\""+isGuozhangField.FieldId+"\":\""+ isGuozhang + "\",\"" + assetMasterSourceFiled.FieldId + "\":{\"value\":\""+ assetSourceValue + "\",\"label\":\""+ assetSourceValue + "\",\"color\":{\"backgroundColor\":\"#4fbbe0\",\"foreColor\":\"#ffffff\"}},\""+ assetAdressField.FieldId + "\":\"" + address + "\",\""+assetShopNameField.FieldId+"\":\"" + shopname + "\",\""+assetAdressDaleiField.FieldId+"\":"+adressDataJson+",\""+assetShopCodeField.FieldId+"\":"+shopDataJson+ ",\""+ assetMasterTopTypeField.FieldId+"\":{\"value\":\""+ assetMasterTopType + "\",\"label\":\""+ assetMasterTopType + "\",\"color\":{\"backgroundColor\":\"#52a8ff\",\"foreColor\":\"#ffffff\"}},\"" + assetBrandField.FieldId + "\":\"\",\"" + invoiceFiled.FieldId + "\":\"0\",\"" + companyNameField.FieldId + "\":" + companyDetail + ",\"" + assetcenterNameField.FieldId + "\":" + centerDetail + ",\"" + comapnyCodeFiled.FieldId + "\":\"" + companyCodeValue + "\",\""+ companyNewNameField.FieldId + "\":\""+companyName+"\",\""+ assetcenterNewNameField .FieldId+ "\":\""+centerName+"\",\"" + centerCodeFiled.FieldId + "\":\"" + centerValue + "\",\"" + applicationSerialNoFiled.FieldId + "\":\"" +applicationSerialNoValue + "\",\"" + applicationRowFiled.FieldId + "\":\"" + applicationRowValue + "\",\"" + purchaseOrderFiled.FieldId + "\":\"" + purchaseOrderValue + "\",\"" + reciveFiled.FieldId + "\":\"" + serialNo + "\",\"version\":\"\"}",
            //                ["vendor"] = ""
            //            }) ;
            //              }

            //        _logger.LogInformation("收货转入库资产列表：" + JsonSerializer.Serialize(assetList));
            //        _logger.LogInformation("收货转入库资产formjson：" + JsonSerializer.Serialize(mainform));
            //        assetInStorage.AssetList = assetList;
            //        JsonObject ret = YideaClient.AddAssetInStorage(assetInStorage);
            //        _logger.LogInformation("收货转入库处理结果" + ret);
            //    }

            //    _logger.LogInformation("结束处理收货转入库");
            //}
            //catch (Exception ex)
            //{
            //    _logger.LogError(ex, "处理收货转入库异常");
            //}

        }
        private List<AssetType> GetAssetTypeFromCache()
        {
            _cache.TryGetValue("AssetType", out var assetValue);
            List<AssetType> assetTypeList = new List<AssetType>();
            if (assetValue != null)
            {
                assetTypeList = ((IEnumerable<dynamic>)assetValue).Select(item => new AssetType
                {
                    Id = item.Id,
                    Name = item.Name,
                    Hierarchy = item.Hierarchy,
                    Code = item.Code
                }).ToList();
            }
            else
            {
                assetTypeList = FromClient.GetAssetTypes(null).ToList();
                _cache.Set("AssetType", assetTypeList, DateTime.Now.AddMinutes(5));
            }
            return assetTypeList;
        }
        protected JsonObject GetAssetTypeByCode(string assetTypeCode)
        {

            List<AssetType> assetTypeList = GetAssetTypeFromCache();

            var assetType = assetTypeList.Where(e => e.Code == assetTypeCode).FirstOrDefault();
            var hierarchy = assetType.Hierarchy.Split('|');
            string hierarchyName = "";
            foreach (var item in hierarchy)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    var topAssetType = assetTypeList.Where(e => e.Id == int.Parse(item)).FirstOrDefault();
                    if (topAssetType != null)
                    {
                        hierarchyName += topAssetType.Name + "/";
                    }
                }
            }
            if (!string.IsNullOrEmpty(hierarchyName))
            {
                hierarchyName = hierarchyName.Substring(0, hierarchyName.Length - 1);
            }
            var topAssetTypeCode= assetTypeList.Where(e => e.Id == int.Parse(hierarchy[0])).FirstOrDefault();
            return new JsonObject { ["hierarchyName"]= hierarchyName ,["topTypeCode"]= topAssetTypeCode .Code};

        }

    }
}
